<template>
  <div class="view-container">
    <div class="app-title-container title-position">
      <modules-title
        title-name="立项详情"
        style="margin-bottom: 20px"
      >
        <template
          v-if="detailData"
          slot="btn"
        >
          <el-button
            plain
            @click="goBack"
          >返回</el-button>
          <template v-if="from !== 'audit'">
            <el-button
              v-if="detailData.info_status == 0"
              plain
              @click="handleDelete"
            >删除</el-button>
            <el-button
              v-if="detailData.info_status == 0"
              type="primary"
              @click="editProjectInfo"
            >编辑</el-button>
            <el-button
              v-if="detailData.info_status == 0"
              type="primary"
              @click="startResearch"
            >
              启动调研
            </el-button>
            <el-button
              v-hasPermi="{
                v: ['project:my:submitReport'],
                isF: detailData.info_status == 1 && isJoin && activeName1 !== '2',
              }"
              type="primary"
              @click="submitReport"
            >
              填写调研报告
            </el-button>
            <el-button
              v-if="detailData.info_status == 2 && detailData.isCreator"
              type="primary"
              @click="startMeeting"
            >
              发起会议
            </el-button>
            <el-button
              v-if="(detailData.info_status == 2 || detailData.info_status == 5) && detailData.isCreator"
              type="primary"
              @click="returnResearchOperation"
            >
              <template>
                <span v-if="detailData.info_status == 2">回退调研</span>
                <span v-else-if="detailData.info_status == 5">启动调研</span>
              </template>
            </el-button>
            <el-button
              v-if="detailData.info_status == 2 && detailData.isCreator"
              :disabled="disApplyResolution"
              type="primary"
              @click="applyResolutionOperation"
            >
              申请决议
            </el-button>
            <!-- <el-button
            v-hasPermi="{v:['project:my:audit'], isF: detailData.info_status==3}"
            type="primary"
            @click="handleAudit"
          >
            决议审批</el-button> -->
            <el-button
              v-hasPermi="{
                v: ['project:my:printLookInfo'],
                isF: detailData.info_status == 6 || detailData.info_status == 10,
              }"
              type="primary"
              @click="printLookInfo"
            >
              打印尽调表
            </el-button>
            <!-- <el-button
              v-hasPermi="{
                v: ['project:my:printLookInfo'],
                isF: detailData.info_status == 6 || detailData.info_status == 10,
              }"
              type="primary"
              @click="exportLookInfo"
            >
              导出尽调表
            </el-button> -->
            <el-button
              v-hasPermi="{
                v: ['project:my:submitProjectApproval'],
                isF: detailData.info_status == 6,
              }"
              type="primary"
              @click="submitProjectApproval"
            >
              发起立项审批
            </el-button>
            <!-- <el-button
            v-hasPermi="{v:['project:my:projectApproval'], isF: detailData.info_status==7}"
            type="primary"
            @click="projectApprovalOperation"
          >
            立项审批
          </el-button> -->
            <el-button
              v-hasPermi="{
                v: ['project:my:printApproval'],
                isF: detailData.info_status == 9,
              }"
              type="primary"
              @click="printApproval"
            >
              打印立项审批表</el-button>
          </template>
        </template>
      </modules-title>
    </div>
    <div
      v-if="detailData"
      class="main-content-container"
    >
      <div class="status-container">
        <status :status-data="statusData" />
      </div>
      <el-tabs
        v-model="activeName1"
        type="border-card"
      >
        <el-tab-pane name="1">
          <div slot="label">
            <i
              class="el-icon-tickets"
              style="margin-right: 5px"
            /><span>基本信息</span>
          </div>
          <div class="baseInfo-container">
            <baseInfo
              :detail-data="detailData"
              :title-show="false"
              :from="from"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane
          v-if="detailData.info_status >= 1"
          name="2"
        >
          <div slot="label">
            <i
              class="el-icon-document-copy"
              style="margin-right: 5px"
            /><span>调研报告</span>
          </div>
          <div
            v-hasPermi="{
              v: ['project:my:submitReport'],
              isF: isJoin || (!isJoin&&detailData.creator_id===userInfo.user.id),
            }"
            class="tab-content"
            style="width: 100%;"
          >
            <div
              v-if="detailData.info_status===1&&departmentList.length>1"
              class="tip-container"
            >
              <p class="tip-title">参与调研部门：</p>
              <div class="department-container">
                <p
                  v-for="(dep, depidx) in departmentList"
                  :key="depidx"
                  class="tag-item"
                >
                  <el-tag
                    :type="dep.if_commit == 1 ? 'success' : 'danger'"
                    size="medium"
                    effect="plain"
                    class="dep-tag"
                    @click="depTagClick(dep, depidx)"
                  >
                    <span>{{ dep.department_name }}</span>
                    <el-tooltip
                      :content="
                        dep.if_commit == 1 ? '已提交调研报告' : '未提交调研报告'
                      "
                      placement="bottom"
                      effect="light"
                    >
                      <i :class="[
                          'icon',
                          dep.if_commit == 1
                            ? 'el-icon-circle-check'
                            : 'el-icon-warning-outline',
                        ]" />
                    </el-tooltip>
                    <i
                      v-if="depIdx===depidx"
                      class="sanjiao el-icon-caret-bottom"
                    />
                  </el-tag>
                </p>
              </div>
            </div>
            <all-look-info
              v-if="isAllSubmit || (!isJoin&&detailData.creator_id===userInfo.user.id&&isAllSubmit)"
              :all-look-info-list="departmentList"
            />
            <look-info
              v-else
              :department-data="departmentData"
              :project-id="detailData.id"
              :department-look-info="departmentLookInfo"
              :list-data="detailData.department_research"
              :from="from"
              :is-join="isJoin"
              @lookInfoSuccess="lookInfoSuccess"
            />
          </div>
          <div
            v-if="!isJoin&&detailData.creator_id!==userInfo.user.id"
            class="noJoin"
          >您所在部门未参与调研或无提交报告的权限</div>
        </el-tab-pane>
      </el-tabs>

      <div
        v-if="detailData"
        class="tab-container"
        style="margin-top: 20px"
      >
        <el-tabs
          v-model="activeName2"
          type="border-card"
        >
          <el-tab-pane name="1">
            <div slot="label">
              <i
                class="el-icon-s-operation"
                style="margin-right: 5px"
              /><span>操作日志</span>
            </div>
            <div class="tab-content">
              <optionLog
                ref="optionLog"
                :project-id="projectId"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane
            v-if="detailData.if_back===1||detailData.info_status>1"
            name="2"
          >
            <div slot="label">
              <i
                class="el-icon-notebook-1"
                style="margin-right: 5px"
              /><span>会议记录</span>
            </div>
            <div class="tab-content">
              <meeting-list :project-id="projectId" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- 决议审批 -->
    <audit-dialog
      ref="auditDialog"
      :project-id="projectId"
      @evaluationSuccess="evaluationSuccess"
    />
    <!-- 立项审批 -->
    <project-approval-dialog
      ref="projectApprovalDialog"
      :project-id="projectId"
      @projectApprovalSuccess="projectApprovalSuccess"
    />
    <!-- 回退调研 -->
    <return-look-info-dialog
      ref="returnLookDialog"
      @returnSuccess="backSuccess"
    />
    <!-- 打印尽调表 -->
    <vue-easy-print
      v-if="detailData"
      ref="printLookInfo"
    >
      <template slot-scope="func">
        <div id="print-template">
          <look-info-print
            :detail-data="detailData"
            :setting-list="settingList"
          />
        </div>
      </template>
    </vue-easy-print>
    <!-- 尽调表导出 -->
    <vue-html2pdf
      v-if="detailData"
      ref="html2Pdf"
      :show-layout="false"
      :float-layout="true"
      :enable-download="true"
      :preview-modal="false"
      :html-to-pdf-options="pdfOptions"
      :paginate-elements-by-height="1754"
      pdf-content-width="100%"
      :margin="[20,20]"
      filename="尽调表"
      :pdf-quality="2"
      :manual-pagination="false"
      pdf-format="a4"
      pdf-orientation="landscape"
    >
      <section
        slot="pdf-content"
        style="padding:40px;"
      >
        <!-- PDF Content Here -->
        <look-info-print
          :detail-data="detailData"
          :setting-list="settingList"
        />
      </section>
    </vue-html2pdf>
    <!-- 打印立项审批表 -->
    <vue-easy-print
      ref="printApproval"
      table-show
    >
      <!-- 你自己编写打印的模板  -->
      <template slot-scope="func">
        <div id="print-template">
          <approval-print
            :detail-data="detailData"
            :get-chinese-number="func.getChineseNumber"
          />
        </div>
      </template>
    </vue-easy-print>
  </div>
</template>

<script>
import {
  projectInfoDetail,
  submitResearch,
  returnResearch,
  applyResolution,
  lookInfoList,
  projectInfoDelete
} from '@/api/projectInformation'

import { lookInfoSet } from '@/api/printSetting'
import { lookInfoPrintData } from '@/assets/js/commonFun'
import VueHtml2pdf from 'vue-html2pdf'

export default {
  name: 'ProjectDetail',
  components: {
    VueHtml2pdf,
    Status: () => import('./modules/status'),
    BaseInfo: () => import('./modules/baseInfo'),
    OptionLog: () => import('./modules/optionLog'),
    LookInfo: () => import('../modules/lookInfo.vue'),
    AllLookInfo: () => import('../modules/allLookInfo.vue'),
    AuditDialog: () => import('../modules/auditDialog.vue'),
    ProjectApprovalDialog: () => import('../modules/projectApprovalDialog.vue'),
    ApprovalPrint: () => import('../modules/approvalPrint.vue'),
    LookInfoPrint: () => import('../modules/lookInfoPrint.vue'),
    MeetingList: () => import('./modules/meetingList.vue'),
    ReturnLookInfoDialog: () => import('../modules/returnLookInfoDialog.vue')
  },
  data() {
    return {
      from: '', // 判断是否为从审批详情页调过来的
      tabs: '',
      isAllSubmit: false,
      activeName1: '1',
      activeName2: '1',
      projectId: '', // 自研立项id
      detailData: null,
      departmentLookInfo: null,
      departmentList: [], // 参与调查报告的部门，以及是否提交报告
      statusData: {
        info_status: 0
      },
      userInfo: null,
      isJoin: false, // 当前部门是否参与调研
      // 自己所在部门信息
      departmentData: {
        department_id: '',
        department_name: ''
      },
      depIdx: -1,
      settingList: [],
      disApplyResolution: false
    }
  },
  computed: {
    pdfOptions() {
      return {
        margin: [5, 5],
        filename: `${this.detailData.project_name}-尽调表`
      }
    }
  },
  // 生命周期 - 创建完成（访问当前this实例）
  created() {
    this.from = this.$route.query.from || ''
    // 是否为提交调研报告
    this.tabs = this.$route.query.tabs
    if (this.tabs && this.tabs === 'subReport') {
      this.activeName1 = '2'
    }
    // 获取当前登录人所在部门的信息
    this.userInfo = this.$store.getters.userInfo
    if (this.userInfo && this.userInfo.user.department) {
      this.departmentData.department_id = this.userInfo.user.department.id
      this.departmentData.department_name =
        this.userInfo.user.department.department_name
    }
    this.projectId = this.$route.query.projectId || ''
    this.getProjectInfoDetail(this.projectId)
  },
  methods: {
    // 返回之后刷新列表
    refreshBack() {
      this.$route.params.refresh = true
      this.$router.back()
    },
    // fetchData() {
    //   this.getDetails().then(() => {
    //     this.getLookInfoList({ id: this.projectId })
    //   })
    // },
    lookInfoSuccess() {
      this.getProjectInfoDetail(this.projectId)
      this.$refs.optionLog.afreshLogList()
    },
    backSuccess() {
      this.getProjectInfoDetail(this.projectId)
    },
    editProjectInfo() {
      this.$router.push({
        name: 'createEdit',
        query: {
          projectId: this.projectId
        }
      })
    },
    submitReport() {
      if (this.activeName1 === '2') {
        this.$message.warning('您当前已在调研报告页面')
      } else {
        this.activeName1 = '2'
      }
    },
    goBack() {
      // this.$router.back()
      this.refreshBack()
    },
    printApproval() {
      this.$refs.printApproval.print()
    },
    depTagClick(dep, depidx) {
      if (dep.if_commit === 0) {
        this.$message({
          type: 'warning',
          message: '该部门还未提交调研报告。'
        })
        return
      }
      // 只有自己提交了报告才可看其他部门的
      if (
        (this.isJoin &&
          this.departmentLookInfo &&
          this.departmentLookInfo.if_commit === 1) ||
        this.detailData.creator_id === this.userInfo.user.id
      ) {
        this.departmentData = {
          department_id: dep.department_id,
          department_name: dep.department_name
        }
        const p = this.detailData.department_research.filter(
          (pl) => pl.department_id === this.departmentData.department_id
        )[0]
        this.departmentLookInfo = p || null
        this.depIdx = depidx
      } else {
        this.$message({
          type: 'warning',
          message: '您没有参与此次调研或还没有提交调研报告，不能查看。'
        })
      }
    },

    // getLookInfoList(params) {
    //   lookInfoList(params).then(res => {
    //     if (res.code === 200) {
    //       this.departmentList = res.data
    //       // 判断当前部门是否参与调研
    //       const p = this.departmentList.filter(
    //         (pl) => pl.department_id === this.departmentData.department_id
    //       )
    //       // 判断是否所有部门都提交了调研报告
    //       this.isAllSubmit = this.departmentList.every(pl => pl.if_commit === 1)
    //       if (p.length) {
    //         this.isJoin = true
    //       }
    //     }
    //   })
    // },

    // 获取详情
    getDetails() {
      return new Promise((resove, rej) => {
        const that = this
        projectInfoDetail({ id: this.projectId }).then((res) => {
          if (res.code === 200) {
            that.projectId = res.data.id
            that.detailData = res.data
            // 需求状态
            that.statusData.info_status = that.detailData.info_status
            // 如果是尽调中，判断该部门是否已提交尽调报告
            if (that.statusData.info_status >= 1) {
              const pidx = that.detailData.department_research.findIndex(
                (pl) => pl.department_id === that.departmentData.department_id
              )
              if (pidx !== -1) {
                that.departmentLookInfo =
                  that.detailData.department_research[pidx] || null
              }
            }
            // 判断当前部门是否参与调研
            const p = that.departmentList.findIndex(
              (pl) => pl.department_id === that.departmentData.department_id
            )
            // 判断是否所有部门都提交了调研报告
            this.isAllSubmit = that.departmentList.every(
              (pl) => pl.if_commit === 1
            )
            if (p !== -1) {
              that.isJoin = true
              that.depIdx = p
            }
            resove()
          }
        })
      })
    },
    // 获取立项详情
    getProjectInfoDetail(id) {
      const that = this
      const datas = { id: id }
      projectInfoDetail(datas).then((res) => {
        if (res.code === 200) {
          that.detailData = res.data
          that.departmentList = res.data.department_research || []
          // 需求状态
          that.statusData.info_status = that.detailData.info_status
          // 判断是否为创建人
          if (this.detailData.creator_id === this.userInfo.user?.id) {
            Object.assign(that.detailData, { isCreator: true })
          } else {
            Object.assign(that.detailData, { isCreator: false })
          }
          // 如果是尽调中，判断该部门是否已提交尽调报告
          if (that.statusData.info_status >= 1) {
            const pidx = that.detailData.department_research.findIndex(
              (pl) => pl.department_id === that.departmentData.department_id
            )
            if (pidx !== -1) {
              that.departmentLookInfo =
                that.detailData.department_research[pidx] || null
            }
          }
          // 判断当前部门是否参与调研
          const p = that.departmentList.findIndex(
            (pl) => pl.department_id === that.departmentData.department_id
          )
          // 判断是否所有部门都提交了调研报告
          this.isAllSubmit = that.departmentList.every(
            (pl) => pl.if_commit === 1
          )
          if (p !== -1) {
            that.isJoin = true
            that.depIdx = p
          } else {
            if (that.detailData.isCreator) {
              that.departmentLookInfo = that.detailData.department_research[0]
              that.depIdx = 0
            }
          }
        }
      })
    },
    // 打印尽调表
    async printLookInfo() {
      let settingArr = []
      // 获取打印设置初始数据
      const res1 = await lookInfoSet({ dictType: 'jd_print_type' })
      if (res1.code === 200) {
        if (res1.code === 200) {
          const obj = res1.data[0]
          if (obj && obj.dict_val) {
            settingArr = JSON.parse(obj.dict_val) || []
          }
        }
      }
      console.log(settingArr, this.departmentList)
      // // 找到打印所需部门、并找出要打印的值
      this.settingList = lookInfoPrintData(settingArr, this.departmentList)
      console.log(this.settingList)
      setTimeout(() => {
        this.$refs.printLookInfo.print()
      }, 50)
    },
    // 导出尽调表
    async exportLookInfo() {
      let settingArr = []
      // 获取打印设置初始数据
      const res1 = await lookInfoSet({ dictType: 'jd_print_type' })
      if (res1.code === 200) {
        if (res1.code === 200) {
          const obj = res1.data[0]
          if (obj && obj.dict_val) {
            settingArr = JSON.parse(obj.dict_val) || []
          }
        }
      }
      console.log(settingArr, this.departmentList)
      // // 找到打印所需部门、并找出要打印的值
      this.settingList = lookInfoPrintData(settingArr, this.departmentList)
      setTimeout(() => {
        this.$refs.html2Pdf.generatePdf()
      }, 50)
    },
    // 发起会议
    startMeeting() {
      // // this.$refs.startMeetingDialog.open()
      // this.$message({
      //   type: 'warning',
      //   message: '会议模块还在开发中'
      // })
      this.$comFun.goMeetingCreate(1, {
        name: this.detailData.project_name,
        id: this.detailData.id
      })
    },
    // 启动调研
    startResearch() {
      const datas = { id: this.projectId }
      submitResearch(datas).then((res) => {
        if (res.code === 200) {
          this.$message.success('启动成功')
          this.getProjectInfoDetail(this.projectId)
          this.$refs.optionLog.afreshLogList()
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 回退调研
    returnResearchOperation() {
      if (this.detailData.info_status === 2) {
        this.$refs.returnLookDialog.open(this.detailData)
      } else {
        const dat = { id: this.projectId }
        returnResearch(dat).then((res) => {
          if (res.code === 200) {
            if (this.detailData.info_status === 2) {
              this.$message.success('回退成功')
            } else if (this.detailData.info_status === 5) {
              this.$message.success('启动成功')
            }
            this.activeName2 = '1'
            this.getProjectInfoDetail(this.projectId)
            this.$refs.optionLog.afreshLogList()
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
        })
      }
    },
    // 申请决议
    applyResolutionOperation() {
      const dat = { id: this.projectId }
      this.disApplyResolution = true
      applyResolution(dat).then((res) => {
        if (res.code === 200) {
          this.getProjectInfoDetail(this.projectId)
          this.$refs.optionLog.afreshLogList()
          this.$message.success('申请决议成功')
        } else {
          this.disApplyResolution = false
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    /** 审批按钮操作 */
    handleAudit() {
      this.$refs.auditDialog.open()
    },
    evaluationSuccess() {
      this.getProjectInfoDetail(this.projectId)
      this.$refs.optionLog.afreshLogList()
    },
    // 提交立项审批
    submitProjectApproval() {
      this.$router.push({
        name: 'submitApproval',
        query: {
          projectId: this.projectId,
          types: 1
        }
      })
    },
    // 立项审批操作
    projectApprovalOperation() {
      this.$refs.projectApprovalDialog.open()
    },
    projectApprovalSuccess() {
      this.getProjectInfoDetail(this.projectId)
      this.$refs.optionLog.afreshLogList()
    },
    /** 删除按钮操作 */
    handleDelete() {
      const that = this
      this.$confirm('删除自研立项信息后，数据将不可恢复，确认删除？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          projectInfoDelete({ id: that.projectId }).then((res) => {
            if (res.code === 200) {
              that.$message({
                type: 'success',
                message: '删除成功',
                duration: 1500,
                onClose: () => {
                  that.$router.back()
                }
              })
            } else {
              that.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        })
        .catch(function() {})
    }
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
@import "@/styles/variables.scss";
.view-container {
  padding-top: 110px;
  .tip-container {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    p {
      margin: 0px;
      padding: 20px 0px;
    }
    .tip-title {
      font-size: $font-size-main;
      color: $font-color-main;
      width: 160px;
      text-align: right;
      padding-right: 12px;
      box-sizing: border-box;
    }
    .department-container {
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;

      .tag-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        .icon {
          margin-left: 4px;
        }
        .el-tag {
          margin-right: 10px;
          position: relative;
          &:hover {
            cursor: pointer;
          }
        }
        .sanjiao {
          font-size: 14px;
          color: #999;
          position: absolute;
          bottom: -12px;
          left: calc(50% - 7px);
        }
      }
    }
  }
  .status-container {
    margin-bottom: 40px;
  }
}

.noJoin {
  font-size: 14px;
}
</style>
